<script lang="ts" setup>
import { markRaw, ref } from 'vue'
import { type FormInstance } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import Input from './Input.vue'
import Textarea from './Textarea.vue'
import InputNumber from './InputNumber.vue'
import Select from './Select.vue'
import Radio from './Radio.vue'
import Checkbox from './Checkbox.vue'
import Switch from './Switch.vue'
import DatePicker from './DatePicker.vue'
import DatePickerRange from './DatePickerRange.vue'
import Upload from './Upload.vue'
defineOptions({
  name: 'FormCom'
})
// 将表单绑定的ref暴露给父组件
const formRef = ref<FormInstance | null>(null)
defineExpose({ formRef })
const props: any = defineProps({
  formData: {
    type: Object,
    default: () => ({})
  },
  formRules: {
    type: Object,
    default: () => ({})
  },

  formColumns: {
    type: Array,
    default: () => []
  },
  labelWidth: {
    type: Number,
    default: 180
  },
  showSearchBtn: {
    type: Boolean,
    default: true
  }
})
const componentsTypes: any = markRaw({
  Input,
  InputNumber,
  Textarea,
  Select,
  Radio,
  Checkbox,
  Switch,
  DatePicker,
  DatePickerRange,
  Upload
})
const emit = defineEmits(['search'])
const handleSearch = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      emit('search')
    }
  })
}
const resetSearch = () => {
  formRef.value?.resetFields()
  handleSearch()
}
</script>

<template>
  <el-card shadow="never" class="search-wrapper">
    <el-form ref="formRef" :model="props.formData" :rules="props.formRules" v-bind="$attrs" label-width="auto">
      <el-row>
        <el-col
          class="col"
          v-for="(column, index) in props.formColumns"
          :key="index"
          :span="column.span || 6"
          :offset="column.offset || 0"
        >
          <template v-if="column.slotName">
            <slot :name="column.slotName" />
          </template>
          <el-form-item :label="column.label" :prop="column.prop" v-else v-bind="column.formItemOpts">
            <component :is="componentsTypes[column.xType]" v-bind="column" v-model="props.formData[column.prop]" />
          </el-form-item>
        </el-col>
        <el-form-item v-if="showSearchBtn">
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-card>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
  :deep(.el-input-number .el-input__inner) {
    text-align: left;
  }
}
.col {
  padding-right: 10px;
}
</style>
